package com.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @ClassName : MyErrorFilter
 * @Author : 司猫子
 * @Date: 2021/4/13 2:12
 */
@Component
public class MyErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        //返回"error"表示异常过滤器,在其他过滤器抛出异常后会执行此过滤器
        return "error";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        final RequestContext context = RequestContext.getCurrentContext();
        final HttpServletResponse response = context.getResponse();
        //获取Zuul的异常响应对象
        final ZuulException exception = (ZuulException)context.getThrowable();
        //设置响应状态码
        response.setStatus(exception.nStatusCode);
        response.setContentType("text/html;charset=utf-8");


        try (PrintWriter out = response.getWriter()){
            out.println("自定义的异常过滤器类<br>异常类型:"+exception.getClass()+"异常信息:"+exception.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
